import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

function setSessionCookie(name: string, value: string): void {
  // 不设置 expires 或 max - age 属性，即为会话 cookie
  document.cookie = `${name}=${value};path=/`;
}

class http {
  constructor() {}

  static create(): AxiosInstance {
    let baseURL = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
    if (process.env.NODE_ENV === 'development') {
      baseURL = '/szgkapi';
      //setSessionCookie('SZ_STANDARD_SESSION', '4e952a56-f347-4ac6-8384-55058c2dd43e');
    }
    const httpService = axios.create({ baseURL: baseURL });
    const cancelToken = axios.CancelToken;

    const source = cancelToken.source();

    httpService.interceptors.response.use(
      (response: AxiosResponse) => {
        switch (response.data.errcode) {
          case 0:
            return response.data.result;
          case 401:
            alert(response.data.errmsg);
            sessionStorage.clear();
            window.location.href = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/rcam/';
            return Promise.reject(response.data.errmsg || 'Error');
          default:
            return Promise.reject(response.data.errmsg || 'Error');
        }
      },
      (error: any) => {
        return Promise.reject(error);
      }
    );

    httpService.interceptors.request.use(
      (request: any) => {
        request.headers = {
          ...request.headers,
          'Cache-Control': 'no-cache'
        };
        return request;
      },
      (error: any) => {
        return Promise.reject(error);
      }
    );
    return httpService;
  }
}

export { http };
